import React, { useState } from 'react';
import { Settings, Search, Filter, Eye, Trash2, Play, Pause, Download, Upload, MoreVertical, AlertCircle, CheckCircle, Package } from 'lucide-react';
import MenuToggle from '../components/MenuToggle';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHeader, TableRow, TableHead } from '@/components/ui/table';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogFooter } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';

const PluginManagement = ({ toggleSidebar }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [filterStatus, setFilterStatus] = useState('all');
  const [selectedPlugins, setSelectedPlugins] = useState([]);
  const [showUploadDialog, setShowUploadDialog] = useState(false);

  // 模拟已安装插件数据
  const [plugins, setPlugins] = useState([
    {
      id: 1,
      name: '文件管理增强',
      version: '2.1.0',
      description: '提供更强大的文件管理功能，支持批量操作和高级搜索',
      status: 'active',
      author: 'DevTeam',
      installDate: '2024-01-15',
      updateDate: '2024-01-20',
      size: '2.3 MB',
      category: 'productivity'
    },
    {
      id: 2,
      name: 'API调试助手',
      version: '1.5.2',
      description: '专业的API测试和调试工具，支持多种请求格式',
      status: 'active',
      author: 'APITools Inc',
      installDate: '2024-01-10',
      updateDate: '2024-01-18',
      size: '4.1 MB',
      category: 'development'
    },
    {
      id: 3,
      name: '数据可视化',
      version: '3.0.1',
      description: '强大的图表和数据可视化组件库',
      status: 'inactive',
      author: 'ChartMaster',
      installDate: '2024-01-08',
      updateDate: '2024-01-16',
      size: '6.8 MB',
      category: 'analytics'
    },
    {
      id: 4,
      name: '主题定制器',
      version: '1.8.0',
      description: '自定义系统主题和样式的强大工具',
      status: 'error',
      author: 'ThemeStudio',
      installDate: '2024-01-05',
      updateDate: '2024-01-14',
      size: '3.5 MB',
      category: 'design'
    },
    {
      id: 5,
      name: '安全扫描器',
      version: '2.2.1',
      description: '检测和防护系统安全漏洞',
      status: 'active',
      author: 'SecureTech',
      installDate: '2024-01-12',
      updateDate: '2024-01-19',
      size: '5.2 MB',
      category: 'security'
    }
  ]);

  const filteredPlugins = plugins.filter(plugin => {
    const matchesSearch = plugin.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         plugin.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         plugin.author.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStatus = filterStatus === 'all' || plugin.status === filterStatus;
    return matchesSearch && matchesStatus;
  });

  const handlePluginSelect = (pluginId) => {
    setSelectedPlugins(prev => 
      prev.includes(pluginId) 
        ? prev.filter(id => id !== pluginId)
        : [...prev, pluginId]
    );
  };

  const handleSelectAll = () => {
    if (selectedPlugins.length === filteredPlugins.length) {
      setSelectedPlugins([]);
    } else {
      setSelectedPlugins(filteredPlugins.map(plugin => plugin.id));
    }
  };

  const handleToggleStatus = (pluginId) => {
    setPlugins(prev => prev.map(plugin => 
      plugin.id === pluginId ? {
        ...plugin,
        status: plugin.status === 'active' ? 'inactive' : 'active'
      } : plugin
    ));
  };

  const handleUninstall = (pluginId) => {
    if (confirm('确定要卸载此插件吗？')) {
      setPlugins(prev => prev.filter(plugin => plugin.id !== pluginId));
      setSelectedPlugins(prev => prev.filter(id => id !== pluginId));
    }
  };

  const getStatusBadge = (status) => {
    const statusConfig = {
      active: { color: 'bg-green-100 text-green-800', text: '已启用', icon: CheckCircle },
      inactive: { color: 'bg-gray-100 text-gray-800', text: '已禁用', icon: Pause },
      error: { color: 'bg-red-100 text-red-800', text: '错误', icon: AlertCircle }
    };
    
    const config = statusConfig[status] || statusConfig.inactive;
    const IconComponent = config.icon;
    
    return (
      <Badge className={`${config.color} hover:${config.color}`}>
        <IconComponent className="w-3 h-3 mr-1" />
        {config.text}
      </Badge>
    );
  };

  const getCategoryBadge = (category) => {
    const categoryConfig = {
      productivity: { color: 'bg-blue-100 text-blue-800', text: '效率工具' },
      development: { color: 'bg-purple-100 text-purple-800', text: '开发工具' },
      analytics: { color: 'bg-orange-100 text-orange-800', text: '数据分析' },
      design: { color: 'bg-pink-100 text-pink-800', text: '设计工具' },
      security: { color: 'bg-red-100 text-red-800', text: '安全工具' }
    };
    
    const config = categoryConfig[category] || categoryConfig.productivity;
    return (
      <Badge variant="secondary" className={`${config.color} hover:${config.color}`}>
        {config.text}
      </Badge>
    );
  };

  const activeCount = plugins.filter(p => p.status === 'active').length;
  const inactiveCount = plugins.filter(p => p.status === 'inactive').length;
  const errorCount = plugins.filter(p => p.status === 'error').length;
  const totalSize = plugins.reduce((sum, plugin) => {
    const size = parseFloat(plugin.size.replace(' MB', ''));
    return sum + size;
  }, 0);

  return (
    <>
      {/* 头部工具栏 */}
      <div className="mt-3">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl flex items-center justify-center">
                  <Settings className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    插件管理
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    管理已安装的插件和扩展功能
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-material-grey-500" />
                <input
                  type="text"
                  placeholder="搜索插件..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10 pr-4 py-2 w-80 border border-material-grey-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors"
                />
              </div>

              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-32">
                  <Filter className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="active">已启用</SelectItem>
                  <SelectItem value="inactive">已禁用</SelectItem>
                  <SelectItem value="error">错误</SelectItem>
                </SelectContent>
              </Select>

              <Dialog open={showUploadDialog} onOpenChange={setShowUploadDialog}>
                <DialogTrigger asChild>
                  <Button variant="outline">
                    <Upload className="w-4 h-4 mr-2" />
                    安装插件
                  </Button>
                </DialogTrigger>
                <DialogContent className="sm:max-w-md">
                  <DialogHeader>
                    <DialogTitle>安装插件</DialogTitle>
                  </DialogHeader>
                  <div className="space-y-4">
                    <div>
                      <Label htmlFor="plugin-file">选择插件文件</Label>
                      <Input
                        id="plugin-file"
                        type="file"
                        accept=".zip,.plugin"
                        className="mt-1"
                      />
                    </div>
                    <div className="text-sm text-material-grey-600">
                      <p>支持的文件格式：.zip, .plugin</p>
                      <p>最大文件大小：50MB</p>
                    </div>
                  </div>
                  <DialogFooter>
                    <Button variant="outline" onClick={() => setShowUploadDialog(false)}>
                      取消
                    </Button>
                    <Button onClick={() => setShowUploadDialog(false)}>
                      安装
                    </Button>
                  </DialogFooter>
                </DialogContent>
              </Dialog>

              <Button className="bg-primary hover:bg-primary-600">
                <Download className="w-4 h-4 mr-2" />
                插件商店
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">已安装插件</p>
                  <p className="text-2xl font-bold text-material-grey-900">{plugins.length}</p>
                </div>
                <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                  <Package className="w-6 h-6 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">已启用</p>
                  <p className="text-2xl font-bold text-green-600">{activeCount}</p>
                </div>
                <div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                  <CheckCircle className="w-6 h-6 text-green-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">已禁用</p>
                  <p className="text-2xl font-bold text-gray-600">{inactiveCount}</p>
                </div>
                <div className="w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center">
                  <Pause className="w-6 h-6 text-gray-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">占用空间</p>
                  <p className="text-2xl font-bold text-orange-600">{totalSize.toFixed(1)} MB</p>
                </div>
                <div className="w-12 h-12 bg-orange-100 rounded-lg flex items-center justify-center">
                  <Download className="w-6 h-6 text-orange-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 插件列表 */}
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-12">
                    <input
                      type="checkbox"
                      checked={selectedPlugins.length === filteredPlugins.length && filteredPlugins.length > 0}
                      onChange={handleSelectAll}
                      className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50"
                    />
                  </TableHead>
                  <TableHead>插件信息</TableHead>
                  <TableHead>分类</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>版本</TableHead>
                  <TableHead>大小</TableHead>
                  <TableHead>安装日期</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredPlugins.map((plugin) => (
                  <TableRow key={plugin.id}>
                    <TableCell>
                      <input
                        type="checkbox"
                        checked={selectedPlugins.includes(plugin.id)}
                        onChange={() => handlePluginSelect(plugin.id)}
                        className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50"
                      />
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        <div className="flex items-center space-x-3">
                          <div className="w-10 h-10 bg-gradient-to-br from-primary/20 to-primary/30 rounded-lg flex items-center justify-center">
                            <Package className="w-5 h-5 text-primary" />
                          </div>
                          <div>
                            <p className="font-medium text-material-grey-900">{plugin.name}</p>
                            <p className="text-sm text-material-grey-500">by {plugin.author}</p>
                          </div>
                        </div>
                        <p className="text-xs text-material-grey-600 ml-13 max-w-md">
                          {plugin.description}
                        </p>
                      </div>
                    </TableCell>
                    <TableCell>
                      {getCategoryBadge(plugin.category)}
                    </TableCell>
                    <TableCell>
                      {getStatusBadge(plugin.status)}
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-material-grey-700">v{plugin.version}</span>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-material-grey-700">{plugin.size}</span>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-material-grey-700">{plugin.installDate}</span>
                    </TableCell>
                    <TableCell className="text-right">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon">
                            <MoreVertical className="w-4 h-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem>
                            <Eye className="w-4 h-4 mr-2" />
                            查看详情
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => handleToggleStatus(plugin.id)}>
                            {plugin.status === 'active' ? (
                              <>
                                <Pause className="w-4 h-4 mr-2" />
                                禁用
                              </>
                            ) : (
                              <>
                                <Play className="w-4 h-4 mr-2" />
                                启用
                              </>
                            )}
                          </DropdownMenuItem>
                          <DropdownMenuItem>
                            <Settings className="w-4 h-4 mr-2" />
                            配置
                          </DropdownMenuItem>
                          <DropdownMenuItem 
                            onClick={() => handleUninstall(plugin.id)}
                            className="text-red-600"
                          >
                            <Trash2 className="w-4 h-4 mr-2" />
                            卸载
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>

            {filteredPlugins.length === 0 && (
              <div className="text-center py-12">
                <div className="w-24 h-24 mx-auto mb-4 bg-material-grey-200 rounded-full flex items-center justify-center">
                  <Package className="w-8 h-8 text-material-grey-500" />
                </div>
                <h3 className="text-lg font-medium text-material-grey-700 mb-2">
                  {searchQuery ? '未找到匹配的插件' : '暂无已安装插件'}
                </h3>
                <p className="text-material-grey-500">
                  {searchQuery ? '尝试使用不同的关键词搜索' : '前往插件商店安装插件来扩展系统功能'}
                </p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </>
  );
};

export default PluginManagement;
